//
//  PhotoSelectCVController.m
//  AndonImagePicker
//
//  Created by 董文博 on 15/1/7.
//  Copyright (c) 2015年 OA. All rights reserved.
//

#import "PhotoSelectCVController.h"

@interface PhotoSelectCVController ()<UICollectionViewDelegate,UICollectionViewDataSource,ImageCellDelegate>
@property (nonatomic,strong) NSMutableArray  *assetsArrM;
@property (nonatomic,strong) NSMutableArray  *selectedAssetsArrM;
@property (nonatomic,strong) NSMutableArray  *indexArrM;
@property (nonatomic,strong) NSArray         *sortedIndexArr;
@property (nonatomic,strong) UIButton        *doneBtn;
@property (nonatomic,strong) UILabel         *selectedNumLabel;
@property (nonatomic,strong) UIButton        *previewBtn;
@property (nonatomic,strong) NSMutableArray  *imageCellArrM;
@end

@implementation PhotoSelectCVController

- (void)viewDidLoad {
    [super viewDidLoad];
    CGRect frame = self.collectionView.frame;
    frame.size.height -= 44;
    self.collectionView.frame = frame;
    
    self.assetsArrM = [[NSMutableArray alloc] init];
    self.indexArrM = [[NSMutableArray alloc] init];
    self.sortedIndexArr = [[NSArray alloc] init];
    self.selectedAssetsArrM = [[NSMutableArray alloc] init];
    self.imageCellArrM = [[NSMutableArray alloc] init];
    self.title = [_group valueForProperty:ALAssetsGroupPropertyName];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStyleDone) target:self action:@selector(cancle)];
    
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    
    UIView *bottomBar = [[UIView alloc] initWithFrame:CGRectMake(0, screenSize.height-44, screenSize.width, 44)];
    bottomBar.backgroundColor = [UIColor groupTableViewBackgroundColor];
    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    doneBtn.frame = CGRectMake(screenSize.width-42, 2, 40, 40);
    [doneBtn setTitle:@"完成" forState:(UIControlStateNormal)];
    [doneBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    doneBtn.alpha = 0.5;
    [doneBtn addTarget:self action:@selector(doneBtnOnClick) forControlEvents:(UIControlEventTouchUpInside)];
    doneBtn.enabled = NO;
    self.doneBtn = doneBtn;
    [bottomBar addSubview:doneBtn];
    
    UIButton *previewBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    previewBtn.frame = CGRectMake(10, 2, 40, 40);
    [previewBtn setTitle:@"预览" forState:(UIControlStateNormal)];
    [previewBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    previewBtn.alpha = 0.5;
    [previewBtn addTarget:self action:@selector(previewBtnOnClick) forControlEvents:(UIControlEventTouchUpInside)];
    previewBtn.enabled = NO;
    self.previewBtn = previewBtn;
    [bottomBar addSubview:previewBtn];
    
    
    UILabel *selectedNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(screenSize.width-140, 0, 100, 44)];
    selectedNumLabel.font = [UIFont systemFontOfSize:14];
    selectedNumLabel.text = @"";
    self.selectedNumLabel = selectedNumLabel;
    [bottomBar addSubview:selectedNumLabel];
    
    [self.view addSubview:bottomBar];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"ImageCell" bundle:nil] forCellWithReuseIdentifier:@"Cell"];
    
    [self.group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if (result) {
            [self.assetsArrM addObject:result];
        }else{
            [self.collectionView reloadData];
        }
    }];
   
    // Register cell classes
    
    // Do any additional setup after loading the view.
}

-(void)previewBtnOnClick{
    AndonImageBrowserController *aibc = [[AndonImageBrowserController alloc] init];
    [self.selectedAssetsArrM removeAllObjects];
    for (id index in self.sortedIndexArr) {
         NSInteger x = [index integerValue];
        [self.selectedAssetsArrM addObject:self.assetsArrM[x]];
    }
    
    NSMutableArray *images = [[NSMutableArray alloc] init];
    
    for (ALAsset *asset in self.selectedAssetsArrM) {
        ALAssetRepresentation* representation = [asset defaultRepresentation];
        UIImage *image = [UIImage imageWithCGImage:[representation fullResolutionImage]];
        [images addObject:image];
    }
    
    aibc.images = images;
    [self.navigationController pushViewController:aibc animated:YES];
}

-(void)doneBtnOnClick{
    AndonImagePickerController *aipc = (AndonImagePickerController *)self.navigationController;
    if ([aipc.delegate respondsToSelector:@selector(imagePickerController:didFinishPickingMediaWithAssets:)]) {
        [self.selectedAssetsArrM removeAllObjects];
        for (id index in self.sortedIndexArr) {
            NSInteger x = [index integerValue];
            [self.selectedAssetsArrM addObject:self.assetsArrM[x]];
        }
        
        [aipc.delegate imagePickerController:aipc didFinishPickingMediaWithAssets:self.selectedAssetsArrM];
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            [self.selectedAssetsArrM removeAllObjects];
            self.sortedIndexArr = nil;
            [self.indexArrM removeAllObjects];
            count = 0;
            self.doneBtn.enabled = NO;
            self.doneBtn.alpha = 0.5;
            self.previewBtn.enabled = NO;
            self.previewBtn.alpha = 0.5;
            self.selectedNumLabel.text = @"";
            for (ImageCell *cell in self.imageCellArrM) {
                cell.selectBtn.selected = NO;
        }
        }];
    }
}

-(void)cancle{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
#warning Incomplete method implementation -- Return the number of sections
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
#warning Incomplete method implementation -- Return the number of items in the section
    return self.assetsArrM.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    ALAsset *result = self.assetsArrM[indexPath.row];
    cell.imageView.image = [UIImage imageWithCGImage:[result thumbnail]];
    cell.imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImageView:)];
    [cell.imageView addGestureRecognizer:tap];
    cell.index = indexPath.row;
    tap.view.tag = cell.index;
    if ([self.indexArrM containsObject:@(cell.index)]) {
        cell.selectBtn.selected = YES;
    }else{
        cell.selectBtn.selected = NO;
    }
    cell.delegate = self;
    return cell;
}

-(void)clickImageView:(UITapGestureRecognizer *)tap
{
    AndonImageBrowserController *aibc = [[AndonImageBrowserController alloc] init];
    NSMutableArray *images = [[NSMutableArray alloc] init];
    ALAsset *asset = self.assetsArrM[tap.view.tag];
    ALAssetRepresentation* representation = [asset defaultRepresentation];
    UIImage *image = [UIImage imageWithCGImage:[representation fullScreenImage]];
    [images addObject:image];
    aibc.images = images;
    [self.navigationController pushViewController:aibc animated:YES];
}

static NSInteger count = 0;

-(void)dealloc
{
    count = 0;
}

-(void)didSelect:(ImageCell *)imageCell index:(NSInteger)index
{
    
    if (imageCell.isSelected) {
        [self.indexArrM addObject:@(imageCell.index)];
        [self.imageCellArrM addObject:imageCell];
        count ++;
    }else{
        count --;
        [self.indexArrM removeObject:@(imageCell.index)];
        [self.imageCellArrM removeObject:imageCell];
    }
    
    if (count>self.maxSelectNum) {
        NSString *message = [NSString stringWithFormat:@"您最多能选择%ld张图片",(long)self.maxSelectNum];
        [[[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        count = self.maxSelectNum;
        imageCell.selectBtn.selected = NO;
        [self.indexArrM removeObject:@(imageCell.index)];
        [self.imageCellArrM removeObject:imageCell];
    }else{
        //[self.indexArrM addObject:@(index)];
        //imageCell.selectBtn.selected = YES;
    }
    NSComparator cmptr = ^(id obj1, id obj2){
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
    self.sortedIndexArr = [self.indexArrM sortedArrayUsingComparator:cmptr];
    
    if ([self.sortedIndexArr count] == 0) {
        self.doneBtn.enabled = NO;
        self.doneBtn.alpha = 0.5;
        self.previewBtn.enabled = NO;
        self.previewBtn.alpha = 0.5;
        self.selectedNumLabel.text = @"";
    }else{
        self.selectedNumLabel.text = [NSString stringWithFormat:@"已选择%ld张图片",(long)[self.sortedIndexArr count]];
        self.doneBtn.alpha = 1;
        self.doneBtn.enabled = YES;
        self.previewBtn.enabled = YES;
        self.previewBtn.alpha = 1;
    }
}

#pragma mark <UICollectionViewDelegate>

/*
 // Uncomment this method to specify if the specified item should be highlighted during tracking
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
 }
 */

/*
 // Uncomment this method to specify if the specified item should be selected
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */

/*
 // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
 }
 
 - (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
 }
 
 - (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
 }
 */

@end
